#include <iostream>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())

set<int> _set;
map<set<int>, int> id_cache;
vector<set<int>> set_cache;

int get_id(set<int>);

int main() {
  int k;

  cin >> k;
  while (k--) {
    int n;
    string op;
    stack<int> _stack;

    cin >> n;
    while (n--) {
      cin >> op;
      if (op[0] == 'P') {
        _stack.push(get_id(_set));
      }
      else if (op[0] == 'D') {
        _stack.push(_stack.top());
      }
      else {
        set<int> x1 = set_cache[_stack.top()];
        _stack.pop();
        set<int> x2 = set_cache[_stack.top()];
        _stack.pop();
        set<int> x;
        if (op[0] == 'U') {
          set_union(ALL(x1), ALL(x2), INS(x));
        }
        else if (op[0] == 'I') {
          set_intersection(ALL(x1), ALL(x2), INS(x));
        }
        else if (op[0] == 'A') {
          x = x2;
          x.insert(id_cache[x1]);
        }
        _stack.push(get_id(x));
      }

      cout << set_cache[_stack.top()].size() << endl;
    }

    cout << "***" << endl;
  }
  return 0;
}

int get_id(set<int> x) {
  if (id_cache.count(x)) {
    return id_cache[x];
  }

  set_cache.push_back(x);
  return id_cache[x] = id_cache.size() - 1;
}
